package com.wcl.demo.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.core.EMConnectionManager;
import com.easemob.exceptions.EaseMobException;
import com.wcl.demo.R;
import com.wcl.demo.db.MessageHelper;
import com.wcl.demo.model.entity.InviteMessage;
import com.wcl.demo.ui.activity.InviteActivity;
import com.wcl.demo.ui.adapter.NewsAdapter;
import com.wcl.demo.utils.ActivityUtils;
import com.wcl.demo.view.CustomToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;


/**
 * Created by dllo on 15/11/17.
 */
public class NewsFragment extends Fragment implements EMContactListener, EMEventListener {

    public static final int CHAT = 0;
    public static final int GROUPCHAT = 1;

    private RelativeLayout invite_relativeLayout;
    private ListView news_list;
    private NewsAdapter adapter;
    private ImageView prompt_imageView;
    private Context context;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    /***
     * 加载布局
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news, null);
    }

    /***
     * 初始化控件
     *
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        news_list = (ListView) view.findViewById(R.id.news_list);
        prompt_imageView = (ImageView) view.findViewById(R.id.prompt_imageView);
        invite_relativeLayout = (RelativeLayout) view.findViewById(R.id.invite_relativeLayout);
        invite_relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startToActivity(getActivity(), InviteActivity.class);
                prompt_imageView.setVisibility(View.GONE);
            }
        });
    }

    private void initView() {
        adapter = new NewsAdapter(getActivity());
        news_list.setAdapter(adapter);
        adapter.addData(loadConversationList());
    }

    /**
     * 获取会话列表
     *
     * @return
     */
    protected List<EMConversation> loadConversationList() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();

        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        // 同步
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     * comparator类是比较用的
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    private MessageHelper helper=new MessageHelper();

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 100) {
                Bundle bundle = msg.getData();
                if (bundle != null) {
                    String username = bundle.getString("username");
                    String reason = bundle.getString("reason");
                    Log.i("lanou", username + "---" + reason + "<------");
                    if (!(helper.getName(username))) {
                        Log.i("lanou","进没进来?");
                        InviteMessage message = new InviteMessage();
                        message.setFrom(username);
                        message.setReason(reason);
                        message.setStatus(0);
                        helper.saveMessage(message);
                    }
                }
                prompt_imageView.setVisibility(View.VISIBLE);
                //  Log.i("lanou", "收到一好友请求." + "  名字:" + username+" 原因:"+reason);
                //   CustomToast.toastShow(getActivity(),"收到一好友请求."+"  名字:"+username+" 原因:"+reason);
            } else if (msg.what == 200) {
                adapter.addData(loadConversationList());
            } else if (msg.what == 300) {
                helper = new MessageHelper();
                Bundle bundle = msg.getData();
                String username = bundle.getString("username");
                InviteMessage message = helper.queryUser(username).get(0);
                message.setFrom(username);
                message.setReason(message.getReason());
                message.setStatus(1);
                helper.updateMessage(message);
            }

            return false;
        }
    });


    /****
     * 写逻辑
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        EMContactManager.getInstance().setContactListener(this);
        EMChat.getInstance().setAppInited();
        initView();


        EMChatManager.getInstance().registerEventListener(this, new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage
                , EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged});
    }

    @Override
    public void onContactAdded(List<String> list) {
        //增加了联系人时回调此方法

        sendBroad();
        Log.i("lanou", "增加联系人");

    }

    @Override
    public void onContactDeleted(List<String> list) {
        //被删除时回调此方法
        sendBroad();
    }

    @Override
    public void onContactInvited(String username, String reason) {
        //收到好友邀请

        sendBroad();

        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("username", username);
        bundle.putString("reason", reason);
        msg.what = 100;
        msg.setData(bundle);
        handler.sendMessage(msg);

        Log.i("lanou", "好友请求");
        Log.i("lanou", "收到一好友请求." + "  名字:" + username + " 原因:" + reason);
        //  CustomToast.toastShow(getActivity(),"收到一好友请求."+"  名字:"+username+" 原因:"+reason);

    }

    @Override
    public void onContactAgreed(String username) {

        sendBroad();
        //好友请求被同意

        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("username", username);
        msg.what = 300;
        msg.setData(bundle);
        handler.sendMessage(msg);

    }

    @Override
    public void onContactRefused(String s) {
        //好友请求被拒绝
    }

    /**
     * 发送广播
     */
    private void sendBroad() {
        Intent intent = new Intent("com.lanou.addFriend");
        context.sendBroadcast(intent);//发送广播
        Log.i("lanou", "onContactAgreed");

    }

    /**
     * 监听事件
     */
    @Override
    public void onEvent(EMNotifierEvent emNotifierEvent) {
        switch (emNotifierEvent.getEvent()) {
            case EventNewMessage: // 普通消息
            {
             //   EMMessage message = (EMMessage) emNotifierEvent.getData();
                refreshMessage();
                break;
            }

            case EventOfflineMessage: {
                refreshMessage();
                break;
            }

            case EventConversationListChanged: {
                refreshMessage();
                break;
            }
            default:
                break;
        }
    }

    private void refreshMessage() {
        handler.sendEmptyMessage(200);
    }

    class News extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("Sysout", "news");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshMessage();
    }
}
